package com.skyjing.askit.java.view.menuviewitem;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.appcompat.widget.AppCompatImageView;


import com.skyjing.askit.R;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

public class MenuViewItem extends AppCompatImageView {
    private int width = -1;
    private int height = -1;
    private Bitmap bitmap;
    private MenuViewMode mode;
    private OnCustomTouch listen;
    private int longPressSpec;
    private boolean isLong = false;
    //计时器
    private long count = -1;
    //长按过程中事件执行定时器
    private Timer timer;

    public void setPressBitmap(Bitmap pressBitmap) {
        this.pressBitmap = pressBitmap;
    }

    public void setNormalBitmap(Bitmap normalBitmap) {
        this.normalBitmap = normalBitmap;
        this.setImageBitmap(normalBitmap);
    }

    public void beClick() {
        if (listen != null) {
            listen.click(mode);
        }
    }

    //控件被按下时所需替换图片
    private Bitmap pressBitmap;
    //控件默认设置图片
    private Bitmap normalBitmap;


    private static class MyHandler extends Handler {
        WeakReference<MenuViewItem> reference;

        MyHandler(MenuViewItem menuViewItem) {
            reference = new WeakReference<>(menuViewItem);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final MenuViewItem item = reference.get();
            switch (msg.what) {
                case 0:
                    if (!item.isLong) {
                        return;
                    }
                    //700ms时间点需要发送数据
                    if (item.listen != null) {
                        item.listen.longPressPoint(item.mode);
                    }
                    if (item.timer == null) {
                        item.timer = new Timer();
                    }
                    item.timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            if (item.listen != null) {
                                item.listen.keepPress(item.mode);
                            }
                        }
                    }, item.longPressSpec, item.longPressSpec);
                    break;
            }
        }
    }

    private Handler mHandler = new MyHandler(this);

    public MenuViewItem(Context context) {
        super(context);
    }

    public MenuViewItem(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MenuViewItem(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.press_img);
        pressBitmap = BitmapFactory.decodeResource(getResources(), ta.getResourceId(R.styleable.press_img_press_res, 0));
        normalBitmap = BitmapFactory.decodeResource(getResources(), ta.getResourceId(R.styleable.press_img_normal_res, 0));
        ta.recycle();
        if (normalBitmap != null) {
            this.setImageBitmap(normalBitmap);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (timer != null) {
            timer = null;
        }
        mHandler.removeMessages(0);
        mHandler = null;
        pressBitmap.recycle();
        normalBitmap.recycle();
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                if (!isInView(event.getX(), event.getY())) {
                    return false;
                }
//                Log.e("TAG", "ACTION_DOWN: ");
                if (pressBitmap != null) {
                    this.setImageBitmap(pressBitmap);
                }
                if (!mHandler.hasMessages(0)) {
                    mHandler.sendEmptyMessageDelayed(0, 720);
                    count = System.currentTimeMillis();
                }
                break;
            case MotionEvent.ACTION_UP:
                this.setImageBitmap(normalBitmap);
                if (System.currentTimeMillis() - count <= 700) {
                    mHandler.removeMessages(0);
                    if (listen != null) {
                        listen.click(mode);
                    }
                } else {
                    //取消长按定时回调
                    if (timer != null) {
                        timer.cancel();
                        timer.purge();
                        timer = null;
                    }
                    if (listen != null) {
                        if (!isLong) {
                            listen.click(mode);
                        } else {
                            listen.longPressUp(mode);
                        }
                    }

                }
                count = -1;
                break;
        }
        return true;
    }


    /**
     * 自定义长按短按接口
     */
    public interface OnCustomTouch {
        /**
         * 短按抬手回调
         *
         * @param mode 控件标签
         */
        void click(MenuViewMode mode);

        /**
         * 长按时间点回调
         *
         * @param mode 控件标签
         */
        void longPressPoint(MenuViewMode mode);

        /**
         * 长按抬手回调
         *
         * @param mode 控件标签
         */
        void longPressUp(MenuViewMode mode);

        /**
         * 连按回调
         *
         * @param mode 控件标签
         */
        void keepPress(MenuViewMode mode);
    }


    /**
     * 点击回调接口
     *
     * @param listen        长按短按回调接口
     * @param longPressSpec 长按事件回调时间间隔
     * @param mode          控件标签
     */
    public void setOnCostomTouch(OnCustomTouch listen, int longPressSpec, MenuViewMode mode) {
        this.listen = listen;
        this.isLong = mode.isLong();
        this.longPressSpec = longPressSpec;
        this.mode = mode;
    }


    /**
     * @param x 触摸的x坐标
     * @param y 触摸的y坐标
     * @return 是否在当前view中
     */
    private boolean isInView(float x, float y) {
        if (width == -1 || height == -1) {
            bitmap = normalBitmap;
            width = getWidth();
            height = getHeight();
        }
        if (null == bitmap || x < 0 || y < 0 || x >= width || y >= height) {
            return false;
        }
        //控件中心点的x y坐标
        int centerX = width / 2;
        int centerY = height / 2;
        //图片位于控件左上角的x y坐标
        int bitmapLeftTopX = centerX - (bitmap.getWidth() / 2);
        int bitmapLeftTopY = centerY - (bitmap.getHeight() / 2);
        //图片位于控件右下角的x y坐标
        int bitmapRightBottomX = centerX + (bitmap.getWidth() / 2);
        int bitmapRightBottomY = centerY + (bitmap.getHeight() / 2);
        if (x <= bitmapLeftTopX || x >= bitmapRightBottomX || y <= bitmapLeftTopY || y >= bitmapRightBottomY) {
            return false;
        }
        float xb = x / width;
        float yb = y / height;
        int pixel = bitmap.getPixel((int) (bitmap.getWidth() * xb), (int) (bitmap.getHeight() * yb));
        return Color.TRANSPARENT != pixel;
    }
}
